import type { AxiosRequestConfig } from 'axios'
import { parse } from 'query-string'
import axios from 'axios'
import dayjs from 'dayjs'
import Cookies from 'universal-cookie'
import type { UserState } from '@/store/modules/user/types'
import type { ResponseData } from '@/plugins/request/types'
import { string2base64 } from '@/utils/string'

interface Oauth2Param {
  /** 微信oauth认证后携带的code */
  code?: string
  /** 应用（此处指公众号）的appid */
  appid: string
  authAppid: string
  /** 当前需要刷新身份有效期的openid */
  authUserid?: string
  /** 企业微信 企业id */
  authQyCorpid?: string
  /** 学校id */
  oauthcampusid?: string | number
}

/**
 * 将用户的token凭证设置到cookie中
 * @param token 微信侧是用户的openid
 */
export const setToken = (token: string) => {
  const cookies = new Cookies()
  cookies.set('JSSSID_COOKIE', `${token}`, {
    domain: location.hostname,
    expires: dayjs().add(30, 'days').toDate(),
    path: '/',
  })
}

/**
 * 根据需要获取用户身份
 *
 * 优先级 code > oauthOpenid 参数互斥
 * 1. code存在则走微信鉴权获取用户最新身份
 * 2. oauthOpenid存在则刷新对应身份有效期，如有身份数据变更则返回身份数据，否则返回空
 * @param params 用户相关身份
 * @returns
 */
export const reFindUserInfo = async (params: Oauth2Param) => {
  const instance = axios.create({
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      'Access-Control-Allow-Origin-Type': '*',
    },
    timeout: 1000 * 10,
  })
  const requestData = { params, readonly: true, async: false }
  const requestParams: AxiosRequestConfig = {
    url: 'wechat_oauth2_getSnsapiBaseOpenid',
    method: 'POST',
    data: JSON.stringify(requestData),
    baseURL: `${window.location.origin}/api/pc/`,
  }
  const response = await instance.request<ResponseData<UserState>>(
    requestParams,
  )
  if (response.data.ret.code === '200') return response.data.data

  return Promise.reject(response.data.ret.msg)
}

/**
 * 更新用户当前身份信息
 * @returns
 */
export const authCurrentCacheUser = async () => {
  const { appid, campusid, corpid, fromauth } = parse(
    location.hash.replace(/(\/|\#)/g, ''),
  )
  const userInfo = useLocalStorage<UserState>(
    'MOBILE_BASE_DATA',
    {} as UserState,
  )

  // 如果appid存在则从本地存储拿取对应身份信息
  if (appid) {
    const appUserInfo = useLocalStorage<UserState>(
      `${appid}-${campusid || userInfo.value.campusid || 'unknown'}`,
      {} as UserState,
    )
    userInfo.value = appUserInfo.value
    userInfo.value.appid = `${appid}`
  }

  const { openid } = userInfo.value
  // 如果本地没有用户信息，则走微信鉴权拿身份做关联
  if (!openid) {
    const path = string2base64(location.hash)
    location.replace(
      `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${origin}/wechatoauth2/${path}&response_type=code&scope=snsapi_userinfo&state=${appid}#wechat_redirect`,
    )
    return Promise.reject(new Error('身份获取失败！'))
  }
  setToken(openid)

  // 身份数据写入状态管理
  const userStore = useUserStore()
  userStore.setUserInfo(userInfo.value)

  // 由于身份权限重要 故同步获取用户身份信息
  if (!fromauth) {
    try {
      const data = await reFindUserInfo({
        appid: `${appid}`,
        authAppid: `${appid}`,
        authQyCorpid: `${corpid || ''}`,
        oauthcampusid: `${campusid || ''}`,
        authUserid: userInfo.value.openid,
      })
      userInfo.value = data
      userStore.setUserInfo(userInfo.value)
    } catch (error) {}
  }
}
